<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-alert type="warning" title="注意:只允许为三级分类设置相关参数" show-icon :closable="false"></el-alert>
      <el-row>
        <el-col style="margin-top:15px;">
          <span style="margin-right:20px">选择商品分类:</span>
          <el-cascader
            :options="cateList"
            :props="cateProps"
            v-model="selectedKeys"
            @change="cateChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <el-tabs v-model="activeName" @tab-click="clicktTriggerTab">
        <el-tab-pane label="动态参数" name="only">
          <el-button
            type="primary"
            @click="showAddDialog"
            :disabled="isBtnDisbaled"
            size="mini"
          >添加参数</el-button>
          <el-table :data="onlyData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  :key="item"
                  v-for="(item,i) in scope.row.attr_vals"
                  @close="closeTag(i,scope.row)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="newTagInputConfirm(scope.row)"
                  @blur="newTagInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  type="primary"
                  plain
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row.attr_id)">
                  <i class="el-icon-edit"></i> 编辑
                </el-button>
                <el-button size="mini" type="danger" @click="removeParams(scope.row.attr_id)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="many">
          <el-button
            type="primary"
            @click="showAddDialog"
            :disabled="isBtnDisbaled"
            size="mini"
          >添加属性</el-button>
          <el-table :data="manyData" stripe border>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag closable :key="item" v-for="item in scope.row.attr_vals">{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="newTagInputConfirm(scope.row)"
                  @blur="newTagInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditDialog(scope.row.attr_id)">
                  <i class="el-icon-edit"></i> 编辑
                </el-button>
                <el-button size="mini" type="danger" @click="removeParams(scope.row.attr_id)">
                  <i class="el-icon-delete"></i> 删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <el-dialog :title="dialogTitle" :visible.sync="isAddDialog" width="60%" @close="closeAddDialog">
      <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRule">
        <el-form-item :label="dialogName" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isAddDialog=false">取消</el-button>
        <el-button type="primary" @click="addAttr">确认</el-button>
      </span>
    </el-dialog>
    <!-- 修改对话框 -->
    <el-dialog
      :title="'修改' + dialogTitle"
      :visible.sync="isEditDialog"
      width="60%"
      @close="closeEditDialog"
    >
      <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="addFormRule">
        <el-form-item :label="dialogName" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditDialog=false">取消</el-button>
        <el-button type="primary" @click="editAttr">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 分类数据列表
      cateList: [],
      // 选中的分类数据
      selectedKeys: [],
      cateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children'
      },
      // 商品参数数据
      onlyData: null,
      // 商品属性数据
      manyData: null,
      // 当前选中的Tbs
      activeName: 'only',
      // 是否显示添加对话框
      isAddDialog: false,
      // 是否显示编辑对话框
      isEditDialog: false,
      editID: null,
      // 编辑属性表单数据
      editForm: {
        attr_name: ''
      },
      // 添加属性表单数据
      addForm: {
        attr_name: ''
      },
      // 添加模式校验规则
      addFormRule: {
        attr_name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      },
      // 编辑模式检验规则
      editFormRule: {
        attr_name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    // 点击切换
    clicktTriggerTab() {
      this.getParmasData()
    },
    // 显示添加对话框
    showAddDialog() {
      this.isAddDialog = true
    },
    // 显示编辑对话框
    showEditDialog(attrID) {
      this.editID = attrID
      this.isEditDialog = true
      this.getOnlyAttr()
    },
    // 关闭添加对话框
    closeAddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    // 关闭编辑对话框
    closeEditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    // 确认添加属性或者
    addAttr() {
      this.$refs.addFormRef.validate(async valida => {
        if (!valida) return
        this.addForm.attr_sel = this.activeName
        const { data: res } = await this.$http.post(
          `categories/${this.cateID}/attributes`,
          this.addForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加失败')
        }
        this.$message.success('添加成功')
        this.getParmasData()
        this.isAddDialog = false
      })
    },
    removeParams(attrID) {
      this.$confirm('此操作将永久删除该属性', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateID}/attributes/${attrID}`
          )
          if (res.meta.status !== 200) {
            return this.$message.error('删除失败')
          }
          this.$message.success('删除成功')
          this.getParmasData()
        })
        .catch(() => {
          this.$message.info('已取消删除')
        })
    },
    // 编辑
    editAttr() {
      this.$refs.editFormRef.validate(async valida => {
        if (!valida) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateID}/attributes/${this.editID}`,
          { attr_sel: this.activeName, attr_name: this.editForm.attr_name }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('编辑失败')
        }
        this.$message.success('编辑成功')
        this.getParmasData()
        this.isEditDialog = false
      })
    },
    // 获取某一项参数数据
    async getOnlyAttr() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes/${this.editID}`
      )
      if (res.meta.status !== 200) {
        return this.$message('获取失败')
      }
      this.editForm = res.data
    },
    // 获取分类数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', { type: 3 })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类失败')
      }
      this.cateList = res.data
      console.log(this.cateList)
    },
    async getParmasData() {
      if (this.selectedKeys.length !== 3) {
        this.selectedKeys = []
        this.onlyData = []
        this.manyData = []
        return
      }
      const { data: res } = await this.$http.get(
        `categories/${this.cateID}/attributes`,
        { params: { sel: this.activeName } }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败')
      }
      res.data.forEach(item => {
        item.inputVisible = false
        item.inputValue = ''
        item.attr_vals = item.attr_vals === '' ? [] : item.attr_vals.split(',')
      })
      if (this.activeName === 'only') {
        this.onlyData = res.data
      } else if (this.activeName === 'many') {
        this.manyData = res.data
      }
    },
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 确认添加新标签
    newTagInputConfirm(row) {
      let inputValue = row.inputValue
      console.log(inputValue)
      row.inputVisible = false
      if (!inputValue) return
      row.attr_vals.push(inputValue)
      this.updateParams(row)
    },
    closeTag(i, row) {
      row.attr_vals.splice(i, 1)
      this.updateParams(row)
    },
    async updateParams(row) {
      const { data: res } = await this.$http.put(
        `categories/${this.cateID}/attributes/${row.attr_id}`,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(',')
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('更新失败')
      }
      this.$message.success('更新成功')
      row.inputValue = ''
    },
    // 参数更改
    cateChange() {
      this.getParmasData()
    }
  },
  computed: {
    // 是否禁用添加按钮
    isBtnDisbaled() {
      return this.selectedKeys.length !== 3
    },
    // 获取参数ID
    cateID() {
      if (this.selectedKeys.length !== 3) return null
      return this.selectedKeys[2]
    },
    // 对话框标题
    dialogTitle() {
      return this.activeName === 'only' ? '添加参数' : '添加属性'
    },
    // 对话框添加名称
    dialogName() {
      return this.activeName === 'only' ? '动态参数' : '静态属性'
    }
  }
}
</script>
<style lang='less' scoped>
.el-tabs {
  margin-top: 15px;
}
.el-tag {
  margin-right: 15px;
}
.el-input {
  width: 120px;
}
</style>
